import axios from 'axios';
import React, { Component } from 'react'

export default class Search extends Component {
  search = (event) => {
    if(event != 'btn') {
      // 回车搜索
      const {keyCode,target:{value}} = event
      if(keyCode !== 13) return
      if(value.trim() === '') {
          alert('输入不能为空')
          return
      }
    }
    // 获取用户的输入
    const {keywordElement: {value:keyWord}} = this // 连续解构赋值+重命名
    // 发送请求前通知APP更新状态
    this.props.updateAppState({
      isFirst: false,
      isLoading: true
    })
    // 发送网络请求
    axios.get(`/api1/search/users?q=${keyWord}`).then(
      response => {
        // 发送请求后通知APP更新状态
        this.props.updateAppState({
          isLoading: false,
          users: response.data.items
        })
      },
      error => {
        // 请求失败了通知APP更新状态
        this.props.updateAppState({
          isLoading: false,
          err: error.message
        })
      }
    )
  }
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索GitHub用户</h3>
        <div>
          <input onKeyUp={this.search} ref={ c => this.keywordElement = c} type="text" placeholder="输入关键词点击搜索"/>&nbsp;
          <button onClick={() => this.search('btn')}>搜索</button>
        </div>
      </section>
    )
  }
}
